#! /usr/local/bin/python

# Web 2.0 API

import cgitb; cgitb.enable()
import cgi
import urllib
import urllib2
from xml.dom import minidom
from xml.dom.minidom import Document

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

file = urllib2.urlopen('http://cs4380.cs.cityu.edu.hk/51158405/blog/api/comment.xml')
data = file.read()
file.close()

xmldoc = minidom.parseString(data)

# get form variables (if desired)
form = cgi.FieldStorage()
if 'id' in form:
    pid = form['id'].value
else:
    pid = ''
if 'type' in form:
    type = form['type'].value
else:
    type = ''

posts = xmldoc.getElementsByTagName("post")
doc = Document()
exist = 'false'
for post in posts:
    _id = getText(post.getElementsByTagName("id")[0].childNodes)
    if pid == _id:
        # retrieve the data of comment post
        exist = 'true'
        comments = post.getElementsByTagName("comment")
        break
        
if type == 'json':
    print 'Content-type: text/x-json'
    print '{"Comments":['
    if exist == 'true':
        for comment in comments:
            print '{"author" : "%s", ' % getText(comment.getElementsByTagName('user')[0].childNodes)
            print '"time" : "%s", ' % getText(comment.getElementsByTagName('time')[0].childNodes)
            print '"content" : "%s"}' % getText(comment.getElementsByTagName('content')[0].childNodes)
    print ']}'
    
else: # xml format
    print 'Content-type: text/xml'
    if exist == 'true':
        result = doc.createElement('Comments')
        for comment in comments:
            result.appendChild(comment)
        print result.toxml()
    else:
        print '<Comments></Comments>'